<?php
JunctionFileCabinet::using("Junction_Core_Exception");
JunctionFileCabinet::using("Junction_Utils_Xml_Parser");
JunctionFileCabinet::package("Junction_Mapping");

/**
 * Factory for generating new instances of the Mapping class.
 * 
 * <p>This class is responsible for constructing mapping classes
 * from mapping files.  It essentially deserializes the class
 * from the passed XML. 
 *
 * @package junction.core
 */
class Junction_Builder_Core {
	
	/**
	 * Construct a new Mapping class from the given mapping file.
	 * 
	 * @throws Junction_Core_Exception
	 *
	 * @param String $mappingFile full path to the file
	 * @return Junction_Core_Mapping
	 */
	public static function buildMapping($mappingFile) {
		try {
			$result = Junction_Utils_Xml_Parser::parseFile($mappingFile);
			$classes = $result->get("class");
			$class = $classes[0];
			// build table
			$table = new Junction_Mapping_Table($class->tablename);
			$table->addKey($class->id->name, $class->id->column);
			foreach ($class->properties as $property) {
				$table->addColumn($property->name, $property->column);
			}
			// build references
			$refs = new Junction_Mapping_References();
			foreach ($class->collections as $collection) {
				$asso = new Junction_Mapping_Association($collection->classname);
				foreach ($collection->columns as $column) {
					$asso->joinOn($column);
				}
				$refs->addReference($collection->name, $asso);
			}

			return new Junction_Mapping_Core($class->classname, $table, $refs);
		} catch (Junction_Utils_Xml_Exception $e) {
			throw new Junction_Core_Exception($e);
		}
	}
}
?>